package com.example.app12_data_storage.activity;

import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.example.app12_data_storage.R;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.nio.charset.StandardCharsets;

/**
 * 演示手机外部文件存储 sdcard
 * @author lijiguo
 */
public class SdcardActivity extends AppCompatActivity {

    private static final String TAG = "SdcardActivity";

    private EditText etSdcardName;

    private EditText etSdcardContent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_sdcard);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.ll_sdcard), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        Log.i(TAG, "onCreate()");

        // 初始化控件
        etSdcardName = findViewById(R.id.et_sdcard_name);
        etSdcardContent = findViewById(R.id.et_sdcard_content);
    }

    /**
     * 保存文件到sd卡
     * @param view 发生点击事件的视图对象
     */
    public void save(View view) {
        // 判断sd卡的状态
        String externalStorageState = Environment.getExternalStorageState();
        if (!Environment.MEDIA_MOUNTED.equals(externalStorageState)) {
            Toast.makeText(this, "SD卡没有挂载!", Toast.LENGTH_SHORT).show();
        }

        // 获取用户输入的文件名和文件内容
        String fileName = etSdcardName.getText().toString();
        if(TextUtils.isEmpty(fileName)) {
            Toast.makeText(this, "文件名不能为空!", Toast.LENGTH_SHORT).show();
        }

        String fileContent = etSdcardContent.getText().toString();
        if (TextUtils.isEmpty(fileContent)) {
            Toast.makeText(this, "文件内容不能为空!", Toast.LENGTH_SHORT).show();
        }

        // 获取sd卡下的文件路径
        String path = Environment.getExternalStorageDirectory().getAbsolutePath();
        String filePath = path + "/" + fileName;

        // 创建输出流
        try (OutputStream out = new FileOutputStream(filePath)) {
            out.write(fileContent.getBytes(StandardCharsets.UTF_8));
        } catch(IOException e) {
            throw new RuntimeException("保存文件失败");
        }

        Toast.makeText(this, "保存完成!", Toast.LENGTH_SHORT).show();

    }

    /**
     * 读取sd卡上的文件
     * @param view 发生点击事件的视图对象
     */
    public void read(View view) {
        // 判断sd卡的状态
        String externalStorageState = Environment.getExternalStorageState();
        if (!Environment.MEDIA_MOUNTED.equals(externalStorageState)) {
            Toast.makeText(this, "SD卡没有挂载!", Toast.LENGTH_SHORT).show();
        }

        // 获取用户输入的文件名和文件内容
        String fileName = etSdcardName.getText().toString();
        if(TextUtils.isEmpty(fileName)) {
            Toast.makeText(this, "文件名不能为空!", Toast.LENGTH_SHORT).show();
        }

        String fileContent = etSdcardContent.getText().toString();
        if (TextUtils.isEmpty(fileContent)) {
            Toast.makeText(this, "文件内容不能为空!", Toast.LENGTH_SHORT).show();
        }

        // 获取sd卡下的文件路径
        String path = Environment.getExternalStorageDirectory().getAbsolutePath();
        String filePath = path + "/" + fileName;

        // 创建输入流
        try (InputStream in = new FileInputStream(filePath);
        OutputStream out = new ByteArrayOutputStream()) {
            byte[] buffer = new byte[1024];
            int len;
            while((len = in.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }

            String content = out.toString();
            // 显示内容
            Toast.makeText(this, "读取到的内容: " + content, Toast.LENGTH_SHORT).show();
        } catch (IOException e) {
            throw new RuntimeException("读取文件失败");
        }
    }
}